package net.courier.remoting.server;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.courier.remoting.ServiceRegistry;

public class InterceptableServiceRegistry implements ServiceRegistry  {
	private static final int INSTANCE_CACHE_SIZE = 64;
	private Map<String, Object> instanceCache = new ConcurrentHashMap<String, Object>(INSTANCE_CACHE_SIZE);
	private List<MethodInvokeInterceptor> interceptors;
	
	public void setServices(Map<String, Object> instances) {
		instanceCache.putAll(instances);
	}
	
	public void setInterceptors(List<MethodInvokeInterceptor> interceptors) {
		this.interceptors = interceptors;
	}
	
	public MethodInvokeInterceptor[] getSortedInterceptors() {
		if(interceptors == null || interceptors.isEmpty()) {
			return null;
		}
		
		Collections.sort(interceptors, new Comparator<MethodInvokeInterceptor>() {

			public int compare(MethodInvokeInterceptor interceptor1, MethodInvokeInterceptor interceptor2) {
				int order1 = interceptor1.getOrder();
				int order2 = interceptor2.getOrder();
				return (order1 - order2);
			}
		});
		
		return (MethodInvokeInterceptor[]) interceptors.toArray();
	}
	
	@Override
	public void bind(String id, Object instance) {
		if(instanceCache.get(id) == null) {
			instanceCache.put(id, instance);
		}
	}
	
	@Override
	public void rebind(String id, Object instance) {
		instanceCache.put(id, instance);
	}
	
	@Override
	public void unbind(String id) {
		instanceCache.remove(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T getService(String id) {
		return (T) instanceCache.get(id);
	}
}
